package com.pyb.java.commonutil.utils;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;

import androidx.core.app.ActivityCompat;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URL;
import java.util.Enumeration;
import java.util.Locale;
import java.util.UUID;

public class DeviceUtils {

    /**
     * 2  * 获取版本号
     * 3  * @return 当前应用的版本号
     * 4
     */
    public static String getVersion() {
        try {
            PackageManager manager = AppUtils.getInstance().getApp()
                    .getPackageManager();
            PackageInfo info = manager.getPackageInfo(AppUtils.getInstance().getApp()
                    .getPackageName(), 0);
            String version = info.versionName;
            return version;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 获取本机的IMEI
     *
     * @return IMEI
     */
    @SuppressLint("MissingPermission")
    public static String getIMEI() {
        String myIMEI = "310260000000000";
        try {
            TelephonyManager mTelephonyManager = (TelephonyManager)
                    AppUtils.getInstance().getApp()
                    .getSystemService(Context.TELEPHONY_SERVICE);
            myIMEI = mTelephonyManager.getDeviceId();//没有获得Phone权限时,这个会崩溃
            if (TextUtils.isEmpty(myIMEI)) {
                myIMEI = getDeviceId();
                if (TextUtils.isEmpty(myIMEI)) {
                    myIMEI = "310260000000000";
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return myIMEI;
    }

    @SuppressLint("MissingPermission")
    public static String getDeviceId() {
        String m_szDevIDShort = "35" + android.os.Build.BOARD.length() % 10
                + android.os.Build.BRAND.length() % 10 + android.os.Build.CPU_ABI.length() % 10
                + android.os.Build.DEVICE.length() % 10 + android.os.Build.DISPLAY.length() % 10
                + android.os.Build.HOST.length() % 10 + android.os.Build.ID.length() % 10
                + android.os.Build.MANUFACTURER.length() % 10 + android.os.Build.MODEL.length() % 10
                + android.os.Build.PRODUCT.length() % 10 + android.os.Build.TAGS.length() % 10
                + android.os.Build.TYPE.length() % 10 + android.os.Build.USER.length() % 10;// 13 位

        String serial = "serial";// 默认serial可随便定义
        try {
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                if (ActivityCompat.checkSelfPermission(
                        AppUtils.getInstance().getApp(),
                        Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
                    // 由于 Android Q 唯一标识符权限的更改会导致
                    // android.os.Build.getSerial() 返回 unknown,
                    // 但是 m_szDevIDShort 是由硬件信息拼出来的，所以仍然保证了UUID 的唯一性和持久性。
                    serial = android.os.Build.getSerial();// Android Q 中返回 unknown
                }
            } else {
                serial = android.os.Build.SERIAL;
            }
        } catch (Exception ignored) {
        }
        return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
    }

    /**
     * 获取本机的IMSI，若无，提供一默认的
     *
     * @return IMSI
     */
    public static String getIMSI() {
        TelephonyManager mTelephonyManager = (TelephonyManager)
                AppUtils.getInstance().getApp()
                .getSystemService(Context.TELEPHONY_SERVICE);
        @SuppressLint("MissingPermission") String myIMSI = mTelephonyManager.getSubscriberId();
        if (myIMSI == null) {
            myIMSI = "310260000000000";
        }
        Log.d("DeviceInfo", "imsi:" + myIMSI);
        return myIMSI;
    }

    /**
     * 获取设备型号
     *
     * @return
     */
    public static String getDeviceType() {
        return android.os.Build.MODEL;
    }

    /**
     * 获取渠道号
     */
    public static String getChannel() {
        String channel = "";
        try {
            ApplicationInfo appInfo = AppUtils.getInstance().getApp().getPackageManager()
                    .getApplicationInfo(AppUtils.getInstance().getApp().getPackageName(),
                            PackageManager.GET_META_DATA);
            channel = appInfo.metaData.getString("UMENG_CHANNEL");
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return channel;
    }

    /**
     * 获取操作系统版本号
     *
     * @return
     */
    public static String getOsVersion() {
        return android.os.Build.VERSION.RELEASE;
    }

    /**
     * 获取软件的版本号
     *
     * @return 1001
     */
    public static int getVersionCode() {
        int versionCode = 0;
        try {
            versionCode = AppUtils.getInstance().getApp().getPackageManager().getPackageInfo(
                    AppUtils.getInstance().getApp().getPackageName(), 0).versionCode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return versionCode;
    }

    /**
     * 获取软件的版本名称
     *
     * @return 1.0.01
     */
    public static String getVersionName() {
        String versionName = "";
        try {
            versionName = AppUtils.getInstance().getApp().getPackageManager().getPackageInfo(
                    AppUtils.getInstance().getApp().getPackageName(), 0).versionName;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return versionName;
    }

    // 获取本地IP函数
    public static String getLocalIPAddress() {
        try {
            for (Enumeration<NetworkInterface> mEnumeration = NetworkInterface
                    .getNetworkInterfaces(); mEnumeration.hasMoreElements(); ) {
                NetworkInterface intf = mEnumeration.nextElement();
                for (Enumeration<InetAddress> enumIPAddr = intf
                        .getInetAddresses(); enumIPAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIPAddr.nextElement();
                    // 如果不是回环地址
                    if (!inetAddress.isLoopbackAddress()) {
                        // 直接返回本地IP地址
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException ex) {
            Log.e("Error", ex.toString());
        }
        return null;
    }

    /**
     * @param content        请求的参数 格式为：name=xxx&pwd=xxx
     * @param encodingString 服务器端请求编码。如GBK,UTF-8等
     * @return
     */
    public static String getAddresses(String content, String encodingString) {
        // 这里调用pconline的接口
        String urlStr = "http://whois.pconline.sscom.cn/ipJson.jsp";
        // 从http://whois.pconline.com.cn取得IP所在的省市区信息
        String returnStr = getResult(urlStr, content, encodingString);
        if (returnStr != null) {
            // 处理返回的省市区信息
            int startIndex = returnStr.indexOf("\"pro");
            int endIndex = returnStr.indexOf(",\"addr");
            if (startIndex > 0 && endIndex > 0 && endIndex > startIndex) {
                returnStr = returnStr.substring(startIndex, endIndex);
                returnStr = returnStr.replaceAll("\"", "").replace("pro:", "")
                        .replace("city:", "").replace("region:", "");
            }
        }
        return returnStr;
    }

    /**
     * @param urlStr   请求的地址
     * @param content  请求的参数 格式为：name=xxx&pwd=xxx
     * @param encoding 服务器端请求编码。如GBK,UTF-8等
     * @return
     */
    private static String getResult(String urlStr, String content, String encoding) {
        URL url = null;
        HttpURLConnection connection = null;
        try {
            url = new URL(urlStr);
            connection = (HttpURLConnection) url.openConnection();// 新建连接实例
            connection.setConnectTimeout(2000);// 设置连接超时时间，单位毫秒
            connection.setReadTimeout(2000);// 设置读取数据超时时间，单位毫秒

            connection.setDoOutput(true);// 是否打开输出流 true|false
            connection.setDoInput(true);// 是否打开输入流true|false
            connection.setRequestMethod("POST");// 提交方法POST|GET
            connection.setUseCaches(false);// 是否缓存true|false
            connection.connect();// 打开连接端口

            DataOutputStream out = new DataOutputStream(
                    connection.getOutputStream());// 打开输出流往对端服务器写数据
            out.writeBytes(content);// 写数据,也就是提交你的表单 name=xxx&pwd=xxx
            out.flush();// 刷新
            out.close();// 关闭输出流
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(), encoding));// 往对端写完数据对端服务器返回数据
            // ,以BufferedReader流来读取
            StringBuffer buffer = new StringBuffer();
            String line = "";
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            reader.close();
            return buffer.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();// 关闭连接
            }
        }
        return null;
    }

    /**
     * 判断是否平板设备
     * @param context
     * @return true:平板,false:手机
     */
    public static boolean isPad(Context context) {
        return (context.getResources().getConfiguration()
                .screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >=
                Configuration.SCREENLAYOUT_SIZE_LARGE;
    }

    private static Locale locale;

    /**
     * 返回手机系统语言
     *
     * @return
     */
    public static String getSystemLanguage() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            locale = AppUtils.getInstance().getApp().getResources().getConfiguration().getLocales().get(0);
        } else {
            locale = AppUtils.getInstance().getApp().getResources().getConfiguration().locale;
        }
        String lang = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && locale.getScript() != null) {
            lang = locale.getLanguage() + "-" + (locale.getScript().equals("Hant") ? "TW" : locale.getScript().equals("Hans") ? "CN" : locale.getCountry());
        } else {
            lang = locale.getLanguage() + "-" + locale.getCountry();
        }
        return lang;
    }

}
